<template>
	<view>
		<!-- <img :src="imgSrc" :class="{w128:true}"
		:style="[styleObj]" v-if="isShowImg"/>
		<view v-for="item in cities" :key="item.id">
			{{item.name}}
		</view>
		<view>
			<button @click="changeImg(20,$event)" type="default">图片切换</button>
		</view> -->
		<button type="primary" @click="uploadImg">上图</button>
		<img :src="imgSrc"/>
	</view>
</template>

<script>
	import {requet,setCache,getCache,chooseImg,uploadFile} from "../../utils/changetopromise.js";
	export default {
		//需要在created中修改data属性，不然
		//会有一个警告
		created() {
			this.isShowImg=false;
		},
		methods:{
			changeImg(index,e){
				this.isShowImg=!this.isShowImg;
				console.log(e);
			},
			async uploadImg(){
				//弹出选择图片的窗口
				let imgObj=await chooseImg(1);
				//获取选中图片的本地路径
				let tempPath=imgObj.tempFilePaths[0];
				//新的文件名，这个文件名就是上传后七牛云保存图片的文件名
				let imgName=Number(Math.random().toString().substr(3,6)+Date.now()).toString(36)+".png";
				//获取上传凭证
				let keyResult = await requet({
					host:"http://qiniukey.quechao.xyz:3060/?key="+imgName,
					header:{},
					method:"GET"
				});
				//上传凭证
				let token = keyResult.data;
				
				//使用token上传图片
				let uploadResult = await uploadFile(
					'https://up.qiniup.com',//华东区上传域名
					tempPath,
					'file',
					{
						region:'ECN',//上传服务器区域编码
						domain:'http://qiniu.quechao.xyz/',
						key:imgName,//图片名称与生成key的时候用的图片名称一致
						token
					}
				);
				let data = JSON.parse(uploadResult.data);
				this.imgSrc = 'http://qiniu.quechao.xyz/'+data.key;
			}
		},
		data() {
			return {
				imgSrc:'',
				isShowImg:true,
				imgSrc:'../../static/398.jpg',
				styleObj:{
					border:"2px solid #f00"
				},
				cities:[
					{id:1,name:"长沙"},
					{id:2,name:"湘潭"},
					{id:3,name:"株洲"},
				]
			};
		}
	}
</script>

<style lang="scss">
.w128{
	width: 128rpx;
	height: 128rpx;
}
</style>
